<template>
  <button @click="scrollToTop" v-show="visible" class="back-to-top">
    回到顶部
  </button>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, onUnmounted } from "vue";

const visible = ref(false);

const handleScroll = () => {
  visible.value = window.scrollY > 100;
  console.log(
    "scroll",
    document.documentElement.scrollTop,
    document.body.scrollTop,
    window.pageYOffset
  );
};

const pageHeight = ref(0);
onMounted(() => {
  // 当组件挂载完成后获取页面高度
  updatePageHeight();
  window.addEventListener("resize", updatePageHeight);
});

function updatePageHeight() {
  pageHeight.value = window.innerHeight;
  console.log("updatePageHeight", pageHeight.value);
  visible.value = window.innerHeight > 100;
}

const scrollToTop = () => {
  console.log('1111',1111);    
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};
// 组件卸载前移除事件监听
onUnmounted(() => {
  window.removeEventListener("resize", updatePageHeight);
});

// onMounted(() => {
//   updateViewportHeight();
//   document.addEventListener("scroll", handleScroll,{ passive: true });
// });

// onBeforeUnmount(() => {
//   document.removeEventListener("scroll", handleScroll,{ passive: true });
// });
</script>

<style scoped>
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 20px;
  background-color: #333;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>
